package com.itheima.advice;

import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.sql.DataSource;

@Component
@Aspect
public class TxManager {
    //配置切点
    @Pointcut("execution(* com.itheima.service.impl.*.*(..))")
    public void pc() {

    }
    @Autowired
    DataSource dataSource;

    PlatformTransactionManager transactionManager = null;
    TransactionDefinition transactionDefinition = null;
    TransactionStatus transactionStatus = null;

    //写事务语句

    //之前先开始事务，创建对象
    @Before("pc()")
    public void before() {
        //创建事务管理器对象，并注入数据源对象
        transactionManager = new DataSourceTransactionManager(dataSource);
        //创建事务定义对象
        transactionDefinition = new DefaultTransactionDefinition();
        //开始事务
        //事务的状态
        transactionStatus = transactionManager.getTransaction(transactionDefinition);
    }

    //后值对象，运行完成后提交事务
    @AfterReturning("pc()")
    public void afterReturning() {
        //提交事务
        transactionManager.commit(transactionStatus);
    }

    //出现异常对象，出现异常后回滚事务
    @AfterThrowing("pc()")
    public void afterThrowing() {
        transactionManager.rollback(transactionStatus);

    }

}
